package com.ruoyi.web.controller.course;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.ex.service.ExService;
import com.ruoyi.ex.service.IExQuestionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.course.domain.CourseExRecord;
import com.ruoyi.course.service.ICourseExRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 课件做题记录Controller
 *
 * @author zzx
 * @date 2023-05-05
 */
@RestController
@RequestMapping("/course/course_ex_record")
public class CourseExRecordController extends BaseController {

    @Autowired private ICourseExRecordService courseExRecordService;
    @Autowired private ExService exService;
    @Autowired private IExQuestionService questionService;


    /**
     * 查询课件做题记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseExRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(CourseExRecord courseExRecord) {
        startPage();
        List<CourseExRecord> list = courseExRecordService.selectCourseExRecordList(courseExRecord);
        return getDataTable(list);
    }

    /**
     * 导出课件做题记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseExRecord:export')")
    @Log(title = "课件做题记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CourseExRecord courseExRecord) {
        List<CourseExRecord> list = courseExRecordService.selectCourseExRecordList(courseExRecord);
        ExcelUtil<CourseExRecord> util = new ExcelUtil<CourseExRecord>(CourseExRecord.class);
        util.exportExcel(response, list, "课件做题记录数据");
    }

    /**
     * 根据课件获取课件做题记录详细信息
     */
    @GetMapping(value = "/{wareId}")
    public AjaxResult getInfo(@PathVariable("wareId") Long wareId) {
        CourseExRecord build = CourseExRecord.builder().userId(getUserId()).deptId(getDeptId()).wareId(wareId).build();
        CourseExRecord courseExRecord = courseExRecordService.selectCourseExRecordByWare(build);
        List<Long> questionIds = questionService.selectExQuestionIdsByCourseWare(wareId);
        //不存在则添加
        if (ObjectUtil.isEmpty(courseExRecord)){
            courseExRecord = build;
            courseExRecord.setAnswerList("{}");
            courseExRecord.setStatus(0);
            courseExRecord.setQuestionIds(questionIds);
            courseExRecordService.insertCourseExRecord(courseExRecord);
        }
        String answerList = courseExRecord.getAnswerList();
        JSONObject entries = JSONUtil.parseObj(answerList);
        Map<Long, Object> map = new HashMap<>();
        entries.forEach((k,v)-> map.put(Long.valueOf(k),v));
        courseExRecord.setAnswerMap(map);
        if (courseExRecord.getStatus().equals(1)){
            Map<Long, Boolean> questionAnswers = new HashMap<>();
            //格式化已回答列表
            Map<Long, Object> answerMap = exService.rightTotal(map,questionIds);
            for (Long questionId : questionIds) {
                questionAnswers.put(questionId,answerMap.containsKey(questionId));
            }
            courseExRecord.setQuestionAnswers(questionAnswers);
        }
        return success(courseExRecord);
    }

    /**
     * 新增课件做题记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseExRecord:add')")
    @Log(title = "课件做题记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CourseExRecord courseExRecord) {
        return toAjax(courseExRecordService.insertCourseExRecord(courseExRecord));
    }

    /**
     * 修改课件做题记录
     */
    @Log(title = "课件做题记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CourseExRecord courseExRecord) throws Exception {
        courseExRecord.setUserId(getUserId());
        courseExRecord.setDeptId(getDeptId());
        List<Long> longs = questionService.selectExQuestionIdsByCourseWare(courseExRecord.getWareId());
        //如果是提交
        if (courseExRecord.getStatus().equals(1)){
            //判断做对的数量
            Map<Long, Object> rightMap = exService.rightTotal(courseExRecord.getAnswerMap(),longs);
            courseExRecord.setRight((long)rightMap.size());
            courseExRecord.setEndTime(new Date());
        }
        return toAjax(courseExRecordService.updateCourseExRecord(courseExRecord));
    }

    /**
     * 删除课件做题记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseExRecord:remove')")
    @Log(title = "课件做题记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(courseExRecordService.deleteCourseExRecordByIds(ids));
    }
}
